// pages/placeorder/placeorder.js
var util = require('../../utils/util.js');

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    CustomBar2: 0,
    Displaytime: 10,
    animation: false,
    expresss_fee:1,
    oder_no:parseInt('1008'+Math.random()*100000000000000),
 
    express_company_id:88888888,
    express_company: '快递休息啦，请勿下单！',
    shopname:"店铺休息中！",
    Notice: "代取1元1一件（小件），体验价5毛。每晚8.30点配送，下单加QQ群关注配送信息，QQ群:954508637",
    time_way: '立即送出',
    address: '',
    index: 0,

    picker: ['苏宁对应存放店铺名称', '圆通对应存放店铺名称', '顺丰对应存放店铺名称'],
    addressee:"",
      building_number:"",
        addressee_phoneno:"",

  },

  show_yx: function (res) {
    // wx.showToast({
    //   title: '延旭未来，改变既是现在！',
    //   icon: "none",
    //   duration: 1500
    // })
    wx.setClipboardData({
      data: res.currentTarget.dataset.link,
      success: res => {
        wx.showToast({
          title: '延旭未来，改变既是现在！微信号已复制:18580015335',
          icon: "none",
          duration: 1000,
        })
      }
    })
  },

  copy_link(res) {
    wx.setClipboardData({
      data: res.currentTarget.dataset.link,
      success: res => {
        wx.showToast({
          title: 'QQ群号已复制:954508637，快去寻找组织吧！',
          icon: "none",
          duration: 1500,
        })
      }
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var that = this
    that.setData({
      express_company_id: options.express_company_id,
      express_company: options.express_company,
      shopname: options.shopname,
      expresss_fee:wx.getStorageSync("configs").Price,
        Notice:wx.getStorageSync("configs").Notice,
      // addressee: wx.setStorageSync("oder_info").addressee,
      // building_number: wx.setStorageSync("oder_info").building_number,
      // addressee_phoneno: wx.setStorageSync("oder_info").addressee_phoneno,
    })
    // if (wx.setStorageSync("oder_info").addressee){

    // }
    // 设置开屏滚动 速度
    setTimeout(() => {
      this.setData({
        animation: true,
        Displaytime: this.data.Notice.length / 3,
        Displaylength: -(this.data.Notice.length / 21)
      })
    }, 600)
    //设置缓存地址
     wx.getStorage({
      key: 'address',
      success: function (res) {
        console.log(res)
        that.setData({
          address: res.data
        })
        console.log(res)
      },
    })
  

  },
  // 提交
  commit(e){
    var that=this
    console.log(e)
    console.log(e.detail.value) 
    var oder_info = e.detail.value
    if (that.data.address.length<2){
      wx.showToast({
        title: '请先填写正确的配送信息/地址（备用）！',
        icon: 'none'
      })
      return
    }else
    if (oder_info.verification_code.length<2){
      wx.showToast({
        title: '请先填写正确的取件码！',
        icon: 'none'
      })
      return
    } else if (oder_info.addressee.length < 2) {
      wx.showToast({
        title: '请先填写收件人姓名！',
        icon: 'none'
      })
      return
    } else if (oder_info.building_number.length < 2){
      wx.showToast({
        title: '请先填写楼号！',
        icon: 'none'
      })
      return
    }  else if (oder_info.addressee_phoneno.length !=11) {
      wx.showToast({
        title: '手机号位数异常，请检查！',
        icon: 'none'
      })
      return
    }
    wx.setStorageSync("oder_info", oder_info)


    // addressee: wx.getStorageSync("addressee"),
    //   building_number: wx.getStorageSync("building_number"),
    //     addressee_phoneno: wx.getStorageSync("addressee_phoneno"),

    // 跳过支付回调直接跳转避免漏单
    // console.log(res)
      const db = wx.cloud.database()
    db.collection("oder_Lists").add({
      data: {
        _id: oder_info.oder_no,
        oder_type: "get",
        build_number: oder_info.build_number,
        addressee: oder_info.addressee,
        addressee_phoneno: oder_info.addressee_phoneno,
        building_number: oder_info.building_number,
        express_company: oder_info.express_company,
        express_company_id: oder_info.express_company_id,
        expresss_fee: oder_info.expresss_fee,
        expresss_fee_num: oder_info.expresss_fee_num,
        oder_no: oder_info.oder_no,
        Alternate_address: that.data.address,
        shopname: oder_info.shopname,
        verification_code: oder_info.verification_code,
        order_status: 0,
        //  timestamp: (Date.parse(new Date())) / 1000,
        // 默认为毫秒级别
        timestamp: Date.parse(new Date()),
        oder_time: util.formatTime_ymdhms(new Date()),
        oder_time_object: new Date(),


      },
      success(res) {
        
        



        wx.switchTab({
          url: '/pages/order/order',
        })

        console.log(res)
        // wx.showToast({
        //   title: '支付中。。。',
        //   icon: "none",
        //   duration: 3000,
        //   success() {
        //     setTimeout(function () {
        //       wx.switchTab({
        //         url: '/pages/order/order',
        //       })
        //     }, 2000)
        //     //  wx.switchTab({
        //     //    url: '/pages/order/order',
        //     //  })
        //   },
        //   complete() {


        //   }
        // })
      }, fail(res) {
        console.log(res)

      }, complete(res) {
        console.log(res)


        //  wx.redirectTo({
        //    url: '/pages/order/order',
        //  })

      }
    })


  //  

    return

// 支付开始
    wx.cloud.callFunction({

      name: 'getPay',

      data: {

        total_fee: parseInt((parseFloat(oder_info.expresss_fee_num).toFixed(2)) * 100),

        attach: 'anything',

        body: oder_info.express_company+" 快递代取订单请注意！",

        out_trade_no: that.data.oder_no,

        times: "first"

      }

    })

      .then(res => {

        wx.requestPayment({

          appId: res.result.appid,

          timeStamp: res.result.timeStamp,

          nonceStr: res.result.nonce_str,

          package: 'prepay_id=' + res.result.prepay_id,

          signType: 'MD5',

          paySign: res.result.paySign,

          success: res => {

            console.log(res)
            const db = wx.cloud.database()
            db.collection("oder_Lists").add({
              data: {
                _id: oder_info.oder_no,
                oder_type: "get",
                build_number: oder_info.build_number,
                addressee: oder_info.addressee,
                addressee_phoneno: oder_info.addressee_phoneno,
                building_number: oder_info.building_number,
                express_company: oder_info.express_company,
                express_company_id: oder_info.express_company_id,
                expresss_fee: oder_info.expresss_fee,
                expresss_fee_num: oder_info.expresss_fee_num,
                oder_no: oder_info.oder_no,
                Alternate_address: that.data.address,
                shopname: oder_info.shopname,
                verification_code: oder_info.verification_code,
                order_status: 1,
                //  timestamp: (Date.parse(new Date())) / 1000,
                // 默认为毫秒级别
                timestamp: Date.parse(new Date()),
                oder_time: util.formatTime_ymdhms(new Date()),
                oder_time_object: new Date(),


              },
              success(res) {
                wx.switchTab({
                  url: '/pages/order/order',
                })

                console.log(res)
                // wx.showToast({
                //   title: '支付中。。。',
                //   icon: "none",
                //   duration: 3000,
                //   success() {
                //     setTimeout(function () {
                //       wx.switchTab({
                //         url: '/pages/order/order',
                //       })
                //     }, 2000)
                //     //  wx.switchTab({
                //     //    url: '/pages/order/order',
                //     //  })
                //   },
                //   complete() {


                //   }
                // })
              }, fail(res) {
                console.log(res)

              }, complete(res) {
                console.log(res)


                //  wx.redirectTo({
                //    url: '/pages/order/order',
                //  })

              }
            })




          },
          fail: res => {

            console.log(res)
            const db = wx.cloud.database()
            db.collection("oder_Lists").add({
              data: {
                _id: oder_info.oder_no,
                oder_type: "get",
                build_number: oder_info.build_number,
                addressee: oder_info.addressee,
                addressee_phoneno: oder_info.addressee_phoneno,
                building_number: oder_info.building_number,
                express_company: oder_info.express_company,
                express_company_id: oder_info.express_company_id,
                expresss_fee: oder_info.expresss_fee,
                expresss_fee_num: oder_info.expresss_fee_num,
                oder_no: oder_info.oder_no,
                Alternate_address: that.data.address,
                shopname: oder_info.shopname,
                verification_code: oder_info.verification_code,
                order_status: 0,
                //  timestamp: (Date.parse(new Date())) / 1000,
                // 默认为毫秒级别
                timestamp: Date.parse(new Date()),
                oder_time: util.formatTime_ymdhms(new Date()),
                oder_time_object: new Date(),


              },
              success(res) {
                console.log(res)
                wx.showToast({
                  title: '支付中。。。',
                  icon: "none",
                  duration: 3000,
                  success() {
                    setTimeout(function () {
                      wx.switchTab({
                        url: '/pages/order/order',
                      })
                    }, 2000)
                    //  wx.switchTab({
                    //    url: '/pages/order/order',
                    //  })
                  },
                  complete() {


                  }
                })
              }, fail(res) {
                console.log(res)

              }, complete(res) {
                console.log(res)


                //  wx.redirectTo({
                //    url: '/pages/order/order',
                //  })

              }
            })




          },
          complete: res => {

            console.log(res)

          },

        })

      })


// 支付结束

return

    // const db = wx.cloud.database()
     db.collection("oder_Lists").add({
       data: {
         _id: oder_info.oder_no,
         oder_type: "get",
         build_number: oder_info.build_number,
         addressee: oder_info.addressee,
         addressee_phoneno: oder_info.addressee_phoneno,
         express_company: oder_info.express_company,
         express_company_id: oder_info.express_company_id,
         expresss_fee: oder_info.expresss_fee,
         expresss_fee_num: oder_info.expresss_fee_num,
         oder_no: oder_info.oder_no,
         Alternate_address: that.data.address,
         shopname: oder_info.shopname,
         verification_code: oder_info.verification_code,
         order_status:0,
        //  timestamp: (Date.parse(new Date())) / 1000,
        // 默认为毫秒级别
         timestamp: Date.parse(new Date()),
         oder_time: util.formatTime_ymdhms(new Date())  ,
         oder_time_object: new Date(),

         
      },
       success(res){
        console.log(res)
       wx.showToast({
         title: '支付中。。。',
         icon:"none",
         duration:3000,
         success(){
           setTimeout(function(){
             wx.switchTab({
               url: '/pages/order/order',
             })
           },2000)
          //  wx.switchTab({
          //    url: '/pages/order/order',
          //  })
         },
         complete(){
           
          
         }
       })
       }, fail(res){
         console.log(res)

       }, complete(res){
         console.log(res)

       
        //  wx.redirectTo({
        //    url: '/pages/order/order',
        //  })

      }
        })


  },
  // 选择
  PickerChange(e) {
    console.log(e);
    this.setData({
      index: e.detail.value
    })
  },
  detail(e) {
    console.log(e)
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
 
    // wx.showToast({
    //   title: '详情功能尚未完善~',
    //   icon: "none"
    // })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  // 获取通讯地址
  getdz() {
    var that = this
    wx.chooseAddress({
      success(res) {
        console.log(res)
        wx.setStorage({
          key: 'address',
          data: res,
        })
        that.setData({
          address: res
        })

      },
      fail(res) {
        console.log(res)
        wx.showModal({
          title: '注意',
          content: '获取你的通讯地址，便于配送！\r\n以及在联系不上你时作为备用！',
          showCancel: true, //是否显示取消按钮
          cancelText: "不必", //默认是“取消”
          cancelColor: '#b9b9b9', //取消文字的颜色
          confirmText: "好的", //默认是“确定”
          confirmColor: '#000000', //确定文字的颜色
          success: function (res) {
            if (res.cancel) {
              //点击取消,默认隐藏弹框
              console.log("用户取消选择！")
            } else {
              //点击确定

              wx.openSetting({
                success(res) {
                  if (res.authSetting['scope.address'] == false) {
                    wx.showModal({
                      title: '注意',
                      content: '亲，获取你的通讯地址只是为了便于送快递 ，麻烦同意下！',
                      showCancel: false, //是否显示取消按钮
                      cancelText: "不必", //默认是“取消”
                      cancelColor: '#b9b9b9', //取消文字的颜色
                      confirmText: "好的吧", //默认是“确定”
                      confirmColor: '#000000', //确定文字的颜色
                      success: function (res) {
                        if (res.cancel) {
                          //点击取消,默认隐藏弹框
                          console.log("用户取消选择！")
                        } else {
                          that.getdz();
                        }
                      }
                    })

                    //点击确定
                  } else {
                    // 二次授权点击确定
                    console.log(res)
                    that.getdz();
                  }
                },
                fail(res) {
                  console.log(res)

                }
              })
              //  wx.getSetting({
              //    success(res){
              //       console.log(res)
              //    },fail(res){
              //      console.log(res)

              //    }
              //  }) 
            }
          },
          fail: function (res) { }, //接口调用失败的回调函数
          complete: function (res) { }, //接口调用结束的回调函数（调用成功、失败都会执行）
        })

      }
    })

  },
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that=this
    this.setData({
      oder_no: parseInt('1008' + Math.random() * 100000000000000 ),
      // addressee: wx.setStorageSync("oder_info").addressee,
      // building_number: wx.setStorageSync("oder_info").building_number,
      // addressee_phoneno: wx.setStorageSync("oder_info").addressee_phoneno,
    })
    wx.getStorage({
      key: 'oder_info',
      success: function(res) {
        console.log(res.data)
        that.setData({
          addressee: res.data.addressee,
          building_number: res.data.building_number,
          addressee_phoneno: res.data.addressee_phoneno,
        })
      },fail(res){
          console.log(res)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})